package cn.edu.gdut.deepcode.utils;

import cn.hutool.core.codec.Base64;
import cn.hutool.core.lang.UUID;
import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.extern.slf4j.Slf4j;

import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.HexFormat;

import static cn.edu.gdut.deepcode.constant.CacheConstant.SHARED_CODE_SEPARATOR;


/**
 * <p>
 * 通用工具类
 * </p>
 *
 * @Author: 暮倦
 * @Since: 2025-04-08  21:23
 * @Version: 1.0.0
 */
@Slf4j
public class CommonUtils {

    public static final ObjectMapper OBJECT_MAPPER = new ObjectMapper();



    public static String calculateSha256(byte[] data) {
        try {
            MessageDigest digest = MessageDigest.getInstance("SHA-256");
            byte[] hash = digest.digest(data);
            return HexFormat.of().formatHex(hash);
        } catch (NoSuchAlgorithmException e) {
            throw new RuntimeException("SHA-256 algorithm not found", e);
        }
    }


    public static void recordErrorInfoAndThrowException(String exceptionInfoConstant, Object exceptionInfoVar, Exception... exceptions) {
        if (exceptions != null && exceptions.length != 0) {
            throw new RuntimeException(String.format(
                    exceptionInfoConstant,
                    exceptionInfoVar == null ? "null" : exceptionInfoVar.toString()),
                    exceptions[0]
            );
        } else {
            throw new RuntimeException(String.format(
                    exceptionInfoConstant,
                    exceptionInfoVar == null ? "null" : exceptionInfoVar.toString())
            );
        }
    }

    public static String generateSalty() {
        return UUID.randomUUID().toString().substring(0, 8);
    }

    public static String encode(Long ownerId,Long canvasId){
        return Base64.encode(ownerId+ SHARED_CODE_SEPARATOR+canvasId+SHARED_CODE_SEPARATOR+System.currentTimeMillis());
    }

    public static String getOwnerIdFromSharedCode(String sharedCode){
        return sharedCode==null?null:decode(sharedCode).split(SHARED_CODE_SEPARATOR)[0];
    }

    public static String decode(String sharedCode){
        return Base64.decodeStr(sharedCode);
    }

}


